package org.weather.data.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * Created by syf on 2018/6/20.
 */

/**
 * 请求网络接口
 */
public class HttpNetRequest {


    public static String netLoad(String urlString, Map<String,String> map) throws Exception{

        URL url = new URL(urlString);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setRequestMethod("POST");

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setAllowUserInteraction(false);

        //开始请求参数的格式修改
        StringBuffer stringBuffer = new StringBuffer();
        String params = "";
        if (map.size() == 1){

            for (String name :
                    map.keySet()) {
                stringBuffer.append(name).append("=").append(java.net.URLEncoder.encode(map.get(name)));
                params = stringBuffer.toString();
            }
        }else {

            for (String name :
                    map.keySet()) {
                stringBuffer.append(name).append("=").append(java.net.URLEncoder.encode(map.get(name))).append("&");

            }

            params = stringBuffer.toString();
            params = params.substring(0,params.length() - 1);
        }

        PrintStream printStream = new PrintStream(urlConnection.getOutputStream());
        printStream.print(params);

        printStream.close();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        String line,result = "";

        while (null != (line = bufferedReader.readLine())){

            result += line;
        }

        bufferedReader.close();
        urlConnection.disconnect();
        return result;
    }
}
